package top.scsoul.pas.controller;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import top.scsoul.pas.bean.XhrResponse;
import top.scsoul.pas.entity.Clazz;
import top.scsoul.pas.entity.Role;
import top.scsoul.pas.entity.Student;
import top.scsoul.pas.entity.User;
import top.scsoul.pas.service.ClazzService;
import top.scsoul.pas.service.RoleService;
import top.scsoul.pas.service.StudentService;
import top.scsoul.pas.service.UserService;
import top.scsoul.pas.utils.ServletUtil;

import javax.servlet.http.HttpSession;
import java.util.ArrayList;
import java.util.List;

@Slf4j
@Controller
public class UserController {
    @Autowired
    UserService userService;

    @Autowired
    RoleService roleService;

    @Autowired
    ClazzService clazzService;
    @Autowired
    StudentService studentService;

    /**
     * 登录页面
     *
     * @return
     */
    @RequestMapping(value = {"login", "/"})
    public String loginPage() {
        return "login";
    }

    /**
     * 欢迎页面
     *
     * @return
     */
    @GetMapping(value = {"welcome", "welcome.html"})
    public String welcome() {
        return "welcome";
    }

    /**
     * 后台模板框架页面
     *
     * @return
     */
    @GetMapping(value = {"main", "main.html"})
    public String main() {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        log.info("权限集合{}", authentication.getAuthorities());
        User user = (User) ServletUtil.getSession().getAttribute("user");
        log.info("session用户{}", user);
        return "main";
    }

    /**
     * 左侧页面
     *
     * @return
     */
    @GetMapping(value = {"left", "left.html"})
    public String left() {
        return "left";
    }

    /**
     * 顶部页面
     *
     * @return
     */
    @GetMapping(value = {"top", "top.html"})
    public String top() {
        return "top";
    }

    /**
     * 教师列表 json
     *
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "api/teacherList")
    public XhrResponse teacherList() {
        List<User> teachers = userService.getTeachers();
        return XhrResponse.success(teachers);
    }

    /**
     * 用户列表分页展示页面
     *
     * @param currentPage
     * @param pageSize
     * @param model
     * @return
     */
    @PreAuthorize("hasAnyRole('ADMIN')")
    @RequestMapping("user/list")
    public String teacherSystem(
            @RequestParam(required = false) int currentPage,
            @RequestParam(required = false) int pageSize,
            Model model) {
        if (currentPage <= 0) {
            currentPage = 1;
        }
        Page<User> userPage = userService.listTeachers(currentPage, pageSize);
        model.addAttribute("userPage", userPage);
        return "user_list";
    }

    /**
     * 添加用户页面
     *
     * @return
     */
    @RequestMapping("user/add")
    public String addUserPage() {
        return "user_add";
    }

    /**
     * 判断用户是否存在接口
     *
     * @param loginName
     * @return
     */
    @ResponseBody
    @RequestMapping("api/userExists")
    public XhrResponse userExists(String loginName) {
        boolean exists = userService.existsUserByLoginName(loginName);
        return XhrResponse.success(exists);
    }
    @PreAuthorize("hasAnyRole('ADMIN')")
    @ResponseBody
    @RequestMapping("api/addUser")
    public XhrResponse addUser(String name, String loginName, @RequestParam(value = "roleIds[]") List<Long> roleIds) {
        boolean exists = userService.existsUserByLoginName(loginName);
        if (exists) {
            return XhrResponse.error("用户已经存在");
        }
        List<Role> roles = roleService.getRoleByIds(roleIds);
        User user = new User();
        user.setName(name);
        user.setLoginName(loginName);
        user.setRoles(roles);
        userService.saveUser(user);
        return XhrResponse.success();
    }
    @PreAuthorize("hasAnyRole('ADMIN')")
    @ResponseBody
    @RequestMapping("api/deleteUser")
    public XhrResponse deleteUser(Long id) {
        userService.deleteUserById(id);
        return XhrResponse.success();
    }
    @PreAuthorize("hasAnyRole('ADMIN')")
    @ResponseBody
    @RequestMapping("api/changeState")
    public XhrResponse changeState(Long id, String state) {
        try {
            userService.changeState(id, state);
        } catch (RuntimeException e) {
            return XhrResponse.error(e.getMessage());
        }
        return XhrResponse.success();
    }
    @PreAuthorize("hasAnyRole('ADMIN')")
    @RequestMapping("user/edit/{id}")
    public String editUserPage(@PathVariable Long id, Model model) {
        User user = userService.getUserById(id);
        model.addAttribute("user", user);
        return "user_edit";
    }

    @ResponseBody
    @RequestMapping("api/updateUser")
    public XhrResponse updateUser(Long id, String name, String loginName, @RequestParam(value = "roleIds[]") List<Long> roleIds) {
        List<Role> roles = roleService.getRoleByIds(roleIds);
        User user = userService.getUserById(id);
        user.setName(name);
        user.setLoginName(loginName);
        user.setRoles(roles);
        userService.saveUser(user);
        return XhrResponse.success();
    }

    /**
     * 获取班主任自己的所有班级
     *
     * @param id 班主任ID
     * @return
     */
    @ResponseBody
    @RequestMapping("api/getSelfClazz")
    public XhrResponse getSelfClazz(Long id) {
        List<Clazz> clazzList = userService.getSelfClazz(id);
        log.info("班主任班级{}", clazzList);
        return XhrResponse.success(clazzList);
    }

    /**
     * 班主任获取自己班级的学生 CURD 页面
     *
     * @param clazzId 提供班级id 不提供就是采用集合中第一条
     * @param session
     * @param model
     * @return
     */
    @RequestMapping("teacher/getSelfUser")
    public String getStudentsByClazzId(@RequestParam(required = false) Long clazzId, HttpSession session, Model model) {
        User user = (User) session.getAttribute("user");
        List<Clazz> clazzList = userService.getSelfClazz(user.getId());
        List<Student> studentList = new ArrayList<>(1);
        Clazz clazz = null;
        if (clazzList.size() == 0) {
            log.info("班主任没有班级");
        } else {
            if (clazzId == null) {
                log.info("clazzId为空");
                clazzId = clazzList.get(0).getId();
            }
            studentList = studentService.getStudentsByClazzId(clazzId);
            clazz = clazzService.getById(clazzId);
        }
        model.addAttribute("studentList", studentList);
        model.addAttribute("clazzList", clazzList);
        model.addAttribute("clazz", clazz);
        return "student_list_of_teacher";
    }


}
